package engine;

import java.util.Vector;

import engine.data.Player;

public final class TimerThread extends Thread {

	private Vector actions = new Vector();

	public static final long SHOWING_TIME = 1000;

	public static final long HIDING_TIME = 500;

	public static final long SLEEP_TIME = 25;

	public TimerThread() {
		start();
	}

	public void run() {
		try {
			long time = System.currentTimeMillis();
			long blinkTime = time;
			short lastactionIndex;
			byte action;
			while (true) {
				time = System.currentTimeMillis();
				if (GameEngine.currPlayer != null && GameEngine.currPlayer.type == Player.HUMAN) {
					if (GameEngine.currPlayer.showOnScr) {
						if (time < blinkTime + TimerThread.SHOWING_TIME) {
							Midlet.canvasEngine.showUnit();
						} else if (time < blinkTime + TimerThread.SHOWING_TIME + TimerThread.HIDING_TIME)
							Midlet.canvasEngine.hideUnit();
						else
							blinkTime = time;
					}
					while (this.actions.size() > 0) {
						lastactionIndex = (short) (this.actions.size() - 1);
						action = ((Byte) this.actions.elementAt(lastactionIndex)).byteValue();
						this.actions.removeElementAt(lastactionIndex);
						switch (action) {
							case UnitAction.MOVE_UP:
							case UnitAction.MOVE_DOWN:
							case UnitAction.MOVE_LEFT:
							case UnitAction.MOVE_RIGHT:
							case UnitAction.MOVE_UP_LEFT:
							case UnitAction.MOVE_UP_RIGHT:
							case UnitAction.MOVE_DOWN_LEFT:
							case UnitAction.MOVE_DOWN_RIGHT:
							case UnitAction.FIRE:
								Midlet.canvasEngine.doAction(action);
								break;
							default:
								break;
						}
					}
				}
				try {
					Thread.sleep(TimerThread.SLEEP_TIME);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(-1);
			// TODO: handle exception
		}
	}

	public void addAction(final byte action) {
		if (GameEngine.currPlayer != null && GameEngine.currPlayer.type == Player.HUMAN)
			this.actions.addElement(new Byte(action));
	}
}
